package org.com.yz.dubbo.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.com.yz.common.util.MySeq;
import org.com.yz.dal.dao.mapper.BankCardMapper;
import org.com.yz.dal.dao.mapper.DepositTransactionMapper;
import org.com.yz.dal.dao.mapper.MchAccntMapper;
import org.com.yz.dal.dao.mapper.MchSubMapper;
import org.com.yz.dal.dao.model.*;
import org.com.yz.dubbo.api.service.IBankCardService;
import org.com.yz.dubbo.api.service.IBathCreateMchSubService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @ClassName BathCreateMchSubServiceImpl
 * @Author wzc
 * @Date 2018/7/25 14:14
 **/
@Service(version = "1.0.0")
public class BathCreateMchSubServiceImpl implements IBathCreateMchSubService {

    @Autowired
    private IBankCardService bankCardService;

    @Autowired
    private MchAccntMapper mchAccntMapper;

    @Autowired
    private MchSubMapper mchSubMapper;

    @Autowired
    private DepositTransactionMapper depositTransactionMapper;

    @Autowired
    private BankCardMapper bankCardMapper;



    public BatchCreateMchSubEs bathCreateMchSubHandel(BatchCreateMchSubEs subEs) throws Exception {

        List<MchAccnt> mchAccntList = subEs.getBizContent( ).getMchAccnts( );
        BatchCreateMchSub res = new BatchCreateMchSub( );          //返回biz_content中的内容
        BatchCreateMchSubEs resTo = new BatchCreateMchSubEs( );    //返回用的biz_content
        List<MchAccnt> resList = new ArrayList<>(mchAccntList.size( ));  //返回的商户信息
        /*List<BankCard> bankCardListNew = new ArrayList<>( );   //存放认证成功的卡号

        for (int i = 0; i < mchAccntList.size( ); i++) {   //子商户列表
            List<BankCard> bankCardList = mchAccntList.get(i).getBank_cards( ); //子商户下的银行卡列表
             for (int j = 0; j < bankCardList.size( ); j++) {
                 BankCard bankCardNew = bankCardList.get(j);

                 //请求接口
                 BankCard bankCard = new BankCard();
                 if("1".equals(bankCardList.get(j).getCardAccntType())){//对私
                     bankCard = bankCardService.bandCardHandle(bankCardNew, subEs.getMchNo( ), subEs.getOutTransNo( ), subEs.getBizType());
                 }else if("0".equals(bankCardList.get(j).getCardAccntType())){//对公
                     bankCard = bankCardService.binkCompanyCard(bankCardNew);
                 }
//                BankCard bankCard = bankCardService.bandCardHandle(bankCardList.get(j), subEs.getMchNo(), subEs.getOutTransNo(), subEs.getBizType());
//                JSONObject jsonObjecta = (JSONObject) JSONObject.parse(result);  //转换为json

                if ("error".equals(bankCard.getStatus())) {  //代表返回失败
                    MchAccnt mchAccnt = new MchAccnt( );
                    mchAccnt.setStatus("2");
                    mchAccnt.setOutMchAccntNo(mchAccntList.get(i).getOutMchAccntNo( ));//商户系统内部子商户账户号
                    mchAccnt.setDesc(bankCardList.get(j).getCardNo());
                    resList.add(mchAccnt);
                    break;
                }

                    if ("success".equals(bankCard.getStatus())) {   //认证成功

                        //处理空字符串 只有银行是储蓄卡状态下
                        if ("0".equals(bankCardNew.getCardType( ))) {
                            if (StringUtils.isEmpty(bankCardNew.getCardCvn( ))) {
                                bankCardNew.setCardCvn(null);
                            }
                            if (StringUtils.isEmpty(bankCardNew.getCardExpireDate( ))) {
                                bankCardNew.setCardExpireDate(null);
                            }
                        }
                        //插入银行卡数据
                        bankCardNew.setStatus("success");//认证状态
                        bankCardNew.setTracNo(String.valueOf(bankCard.getTracNo());//追踪号
                        bankCardNew.setCreateTime(new Date( ));
                        bankCardNew.setUpdateTime(new Date( ));
                        bankCardListNew.add(bankCardNew);     //成功先存起来
                        //失败直接跳出卡号循环，直到最后一条数据为成功的状态才插入
                        if (j == bankCardList.size( ) - 1) {
                            // 插入子商户信息 并返回子商户号

                            String results= createMchSub(mchAccntList.get(i), subEs.getOutTransNo( ),subEs.getMchNo( ));
                            List<BankCard> returnBankList = new ArrayList<>( );   //该商户所有成功的卡号集合
                            BankCard bankCardRes = new BankCard( );     //返回的只要卡号
                            for (BankCard bankCardInsert : bankCardListNew) {
                                bankCardInsert.setMchNo(subEs.getMchNo( ));//商户号
                                bankCardInsert.setMchAccntNo(results);//子商户号
                                //插入之前先效验当前子商户下有没有此卡存在
                                BankCard isBank=isBankCard(bankCardInsert);
                                if(isBank==null){
                                    bankCardService.inster(bankCardInsert);
                                }
                                bankCardRes.setCardNo(bankCardInsert.getCardNo( ));     //返回用的卡对象
                                returnBankList.add(bankCardRes);
                            }
                            //所有银行卡号认证成功后返回的数据
                            MchAccnt mchAccnt = new MchAccnt( );
                            mchAccnt.setStatus("1");
                            mchAccnt.setOutMchAccntNo(mchAccntList.get(i).getOutMchAccntNo( ));//商户系统内部子商户账户号
                            mchAccnt.setMchAccntNo(results);   //子商户账户号
                            mchAccnt.setDesc(null);
                            mchAccnt.setBank_cards(returnBankList);   //成功的卡集合
                            resList.add(mchAccnt);
                        }
                    }
                    if ("0".equals(jsonObjecta.get("auth_status"))  || "3".equals(jsonObjecta.get("auth_status"))) {   //待认证  认证处理中
                        MchAccnt mchAccnt = new MchAccnt( );
                        //银行卡数据
                        if("0".equals(jsonObjecta.get("auth_status"))){
                            bankCardNew.setStatus("to_verify");   //待认证
                        }else {
                            bankCardNew.setStatus("to_handle");   //认证处理中
                        }

                        bankCardNew.setTracNo(String.valueOf(jsonObjecta.get("trac_no")));
                        bankCardNew.setCreateTime(new Date( ));
                        bankCardNew.setUpdateTime(new Date( ));
                        bankCardListNew.add(bankCardNew);     //先存起来

                        if (j == bankCardList.size( ) - 1) {   //0和3的为最后一条
                            List<BankCard> returnBankList = new ArrayList<>( );   //该商户所有成功的卡号集合
                            BankCard bankCardRes = new BankCard( );     //返回的只要卡号
                            for (BankCard bankCardInsert : bankCardListNew) {
                                BankCard isBank=isBankCard(bankCardInsert);  //插入之前先效验当前子商户下有没有此卡存在
                                if(isBank==null){
                                    bankCardService.inster(bankCardInsert);
                                }
                                bankCardRes.setCardNo(bankCardInsert.getCardNo( ));
                                returnBankList.add(bankCardRes);
                            }
                            mchAccnt.setBank_cards(returnBankList);   //将前面成功的数据放入卡号集合，未知的放入desc
                        }

                        mchAccnt.setStatus("3");
                        mchAccnt.setOutMchAccntNo(mchAccntList.get(i).getOutMchAccntNo( ));//商户系统内部子商户账户号
                        mchAccnt.setDesc(bankCardList.get(i).getCardNo( ));
                        resList.add(mchAccnt);

                    }
                    if ("2".equals(jsonObjecta.get("auth_status"))) {   //认证失败
                        MchAccnt mchAccnt = new MchAccnt( );
                        mchAccnt.setStatus("2");
                        mchAccnt.setDesc(bankCardList.get(i).getCardNo( ));
                        mchAccnt.setOutMchAccntNo(mchAccntList.get(i).getOutMchAccntNo( ));//商户系统内部子商户账户号
                        resList.add(mchAccnt);
                        break;     //失败跳出循环
                    }
            }

        }*/

        res.setMchAccnts(resList);
        resTo.setBizContent(res);
        return resTo;
    }




    /**
     * @Description: 效验该子商户银行卡号是否存在
     * @param  bankCard
     * @author wzc
     * @date 2018/7/20 14:56
     * */
    public BankCard  isBankCard(BankCard bankCard){
        BankCard bankCard1=new BankCard();
        bankCard1.setMchAccntNo(bankCard.getMchAccntNo());
        bankCard1.setCardNo(bankCard.getCardNo());
        bankCard1.setStatus("success");
        List<BankCard> list=bankCardMapper.select(bankCard1);
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }




    /**
     * @Description:插入子商户
     * @param
     * @author wzc
     * @date 2018/7/25 15:30
     * */
    public String createMchSub(MchAccnt accnt, String outTraNo, String mchNo) {

        MchAccnt accnt1 = null;
        //外部子商户号已存在，返回失败，但是返回信息里加上子商户账号
        accnt1 = new MchAccnt( );
        accnt1.setOutMchAccntNo(outTraNo);
        accnt1.setMchNo(mchNo);
        MchAccnt mchAccnt2 =selectAccntInfo(accnt);
        if (mchAccnt2 != null) {
            return mchAccnt2.getMchAccntNo();   //已存在就返回原先的子商户号
        }

        Map resultMap = new HashMap( );
        DepositTransaction des = new DepositTransaction( );
        //生成子商户账户
        String mchAccntNo = MySeq.getTrans( );//子商户账号
        des.setTransactionNo(UUID.randomUUID( ).toString( ).replace("-", "").toLowerCase( ));//事务号
        des.setOutTransNo(outTraNo);//外部追踪号
        des.setIdMchAccntChargeUp(0);
        des.setCreateTime(new DateTime( ));//创建时间
        des.setTransactionType("create");//事务类型
        des.setUpdateTime(new DateTime( ));//更新时间
        des.setMchNo(mchNo);//商户号
        //更新事务表
        depositTransactionMapper.insert(des);
        //更新账户表
        accnt.setMchAccntNo(mchAccntNo);//子商户账号
        accnt.setMchNo(mchNo);//商户号
        accnt.setSettleDuration("T1");//结算周期
        accnt.setAccntType("mchsub");//后面应改未字典项
        accnt.setCreateTime(new DateTime( ));//创建时间
        mchSubMapper.insert(accnt);


        return mchAccntNo;
    }


    public MchAccnt selectAccntInfo(MchAccnt accnt) {
        List<MchAccnt> list = mchAccntMapper.select(accnt);
        if(list.size()>0){
            return list.get(0);//存在重复的
        }
        return null;
    }

}

